package com.dlc.apk.service.log.impl

import com.dlc.apk.api.ApiManager
import com.dlc.apk.api.BaseResponseModel
import com.dlc.apk.service.log.ILogService
import com.dlc.apk.utils.DeviceUtil
import com.dlc.apk.utils.LogPlus
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashMap


class LogService : ILogService {
    override fun uploadLog(file: File) {
        val params = HashMap<String, RequestBody>()
        params["macNo"] = RequestBody.create(MediaType.parse("text/plain"), DeviceUtil.androidId)
        params["date"] = RequestBody.create(MediaType.parse("text/plain"), SimpleDateFormat("yyyyMMdd").format(Date()))
        params["packageName"] = RequestBody.create(MediaType.parse("text/plain"), DeviceUtil.packageName!!)
        //val requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file)
        val requestFile: RequestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file)
        // MultipartBody.Part  和后端约定好Key，这里的name是用"file"
        val body = MultipartBody.Part.createFormData("file", file.name, requestFile)
        ApiManager.instance.apiService
            .uploadLog(params = params, file = body)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<BaseResponseModel<Any?>> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: BaseResponseModel<Any?>) {
                    LogPlus.e("###上传日志文件结果,response->$t")
                }

                override fun onError(e: Throwable) {
                    LogPlus.e("###上传日志文件失败,${LogPlus.getStackTraceInfo(e)}")
                }

                override fun onComplete() {
                }
            })
    }
}